/**  
 * @fileOverview 非flash上传附件
 * @author will
 * @version 1.0  
 */  
var isIE = (document.all) ? true : false;

var $will = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    };
  }
};

var Extend = function(destination, source) {
	for (var property in source) {
		destination[property] = source[property];
	}
};

var Bind = function(object, fun) {
	return function() {
		return fun.apply(object, arguments);
	};
};
var Each = function(list, fun){
	for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
};
//文件上传类
var FileUpload = Class.create();
FileUpload.prototype = {
  //表单对象，文件控件存放空间
  initialize: function(form, folder, options) {
	
	this.Form = $will(form);//表单
	this.Folder = $will(folder);//文件控件存放空间
	this.Files = [];//文件集合
	
	this.SetOptions(options);
	
	this.FileName = this.options.FileName;
	this._FrameName = this.options.FrameName;
	this.Limit = this.options.Limit;
	this.Distinct = !!this.options.Distinct;
	this.ExtIn = this.options.ExtIn;
	this.ExtOut = this.options.ExtOut;
	
	this.onIniFile = this.options.onIniFile;
	this.onEmpty = this.options.onEmpty;
	this.onNotExtIn = this.options.onNotExtIn;
	this.onExtOut = this.options.onExtOut;
	this.onLimite = this.options.onLimite;
	this.onSame = this.options.onSame;
	this.onFail = this.options.onFail;
	this.onIni = this.options.onIni;
	if(!this._FrameName){
		this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000);
		//为每个实例创建不同的iframe
		var oFrame = false ? document.createElement("<iframe name=\"" + this._FrameName + "\">") : document.createElement("iframe");
		//为ff设置name
		oFrame.name = this._FrameName;
		oFrame.style.display = "none";
		//在ie文档未加载完用appendChild会报错
		document.body.insertBefore(oFrame, document.body.childNodes[0]);
	}
	
	//设置form属性，关键是target要指向iframe
	this.Form.target = this._FrameName;
	this.Form.method = "post";
	//注意ie的form没有enctype属性，要用encoding
	this.Form.encoding = "multipart/form-data";
	//整理一次
	this.Ini();
  },
  //设置默认属性
  SetOptions: function(options) {
    this.options = {//默认值
		FileName:	"filename",//文件上传控件的name，配合后台使用
		FrameName:	"",//iframe的name，要自定义iframe的话这里设置name
		onIniFile:	function(){},//整理文件时执行(其中参数是file对象)
		onEmpty:	function(){},//文件空值时执行
		Limit:		10,//文件数限制，0为不限制
		onLimite:	function(){},//超过文件数限制时执行
		Distinct:	true,//是否不允许相同文件
		onSame:		function(){},//有相同文件时执行
		ExtIn:		["csv","doc","docx","xls","rar","zip","txt","pdf","png","bmp","xlsx","gif","ppt","vsd","pptx","gif","jpg","rar","zip","swf"],//允许后缀名
		onNotExtIn:	function(){},//不是允许后缀名时执行
		ExtOut:		[],//禁止后缀名，当设置了ExtIn则ExtOut无效
		onExtOut:	function(){},//是禁止后缀名时执行
		onFail:		function(){},//文件不通过检测时执行(其中参数是file对象)
		onIni:		function(){}//重置时执行
    };
    Extend(this.options, options || {});
  },
  //整理空间
  Ini: function() {
	//整理文件集合
	this.Files = [];
	//整理文件空间，把有值的file放入文件集合
	Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){
		if(o.type == "file"){o.value && this.Files.push(o); this.onIniFile(o); }
	}));
	//插入一个新的file
	var file = document.createElement("input");
	file.name = this.FileName; file.type = "file"; file.onchange = Bind(this, function(){ this.Check(file); this.Ini(); });
	this.Folder.appendChild(file);
	//执行附加程序
	this.onIni();
  },
  //检测file对象
  Check: function(file) {
	//检测变量
	var bCheck = true;
	//空值、文件数限制、后缀名、相同文件检测
	if(!file.value){
		bCheck = false; this.onEmpty();
	} else if(this.Limit && this.Files.length >= this.Limit){
		bCheck = false; this.onLimite();
	} else if(!!this.ExtIn.length && !RegExp("\.(" + this.ExtIn.join("|") + ")$", "i").test(file.value)){
		//检测是否允许后缀名
		bCheck = false; this.onNotExtIn();
	} else if(!!this.ExtOut.length && RegExp("\.(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) {
		//检测是否禁止后缀名
		bCheck = false; this.onExtOut();
	} else if(!!this.Distinct) {
		Each(this.Files, function(o){ if(o.value == file.value){ bCheck = false; } });
		if(!bCheck){ this.onSame(); }
	}
	//没有通过检测
	!bCheck && this.onFail(file);
  },
  //删除指定file
  Delete: function(file) {
	//移除指定file
	this.Folder.removeChild(file); this.Ini();
  },
  //删除全部file
  Clear: function() {
	//清空文件空间
	Each(this.Files, Bind(this, function(o){ this.Folder.removeChild(o); })); this.Ini();
  }
};
/**
 * type---id标记
 * eno---eno
 * eventType---itsm-request
 * createor---fullName
 * tabsId ----show_request_effectAttachment
 */
function initFileUpload(type,eno,eventType,createor,tabsId,valueId,fileList){
	if(lang.indexOf("en")>=0){
		$will("idFile"+type).style.width="135px";
	}else{
		$will("idFile"+type).style.width="94px";
	}
	
	$will("idFile"+type).style.background="url(../images/icons/addfile_"+lang+".png) left top no-repeat";
	$will("idFile"+type).onmouseover=function(){ 
		$will("idFile"+type).style.background="url(../images/icons/ahover_addfile_"+lang+".png) left top no-repeat";
	};
	$will("idFile"+type).onmouseout=function(){ 
		$will("idFile"+type).style.background="url(../images/icons/addfile_"+lang+".png) left top no-repeat";
	};
	var fu = new FileUpload("uploadForm"+type, "idFile"+type, { 
		onIniFile: function(file){ file.value ? file.style.display = "none" : this.Folder.removeChild(file); },
		onEmpty: function(){ msgAlert("请选择一个文件","info"); },
		onLimite: function(){ msgAlert("超过上传限制","info"); },
		onSame: function(){ msgAlert("已经有相同文件","info"); },
		onNotExtIn:	function(){ msgAlert("不支持上传此格式的文件","info"); },
		onFail: function(file){ this.Folder.removeChild(file); },
		onIni: function(){
			//显示文件列表
			var arrRows = [];
			if(this.Files.length){
				var oThis = this;
				Each(this.Files, function(o){
					var a = document.createElement("a"); a.innerHTML = i18n.Cancel; a.href = "javascript:void(0);";
					a.onclick = function(){ oThis.Delete(o); return false; };
					arrRows.push([o.value, a]);
				});
			} else { arrRows.push(["<font color='gray'>"+i18n.do_not_add_files+"</font>", "&nbsp;"]); }
			AddList(arrRows,type);
			//设置按钮
			//$will("idBtnupload").disabled = $will("idBtndel").disabled = this.Files.length <= 0;
		}
	});

	//$will("idLimit"+type).innerHTML = fu.Limit;
/*	if(fu.ExtIn.length>0)
		$will("idExt"+type).innerHTML = "只允许上传"+fu.ExtIn.join("，");
*/
	$will("idBtndel"+type).onclick = function(){ fu.Clear(); };
	$will("idBtnupload"+type).onclick = function(){
		var uploadFileNames = "";//要上传的文件名字符串
		var hasUploadFileName = "";  //已上传的文件名字符串
		var hasUploadFileSoonName = "";  //非知识库已上传的文件名字符串
		var hasUploadFileKnowledgeName = ""; //知识库上传的文件名字符串
		$("#"+fileList+" a[target='_blank']").each(function(){  //遍历每个已经上传的文件名并组合在一起
			hasUploadFileName += "-s="+$(this).html();
		});
		
		$("#"+fileList+" div").each(function(){ //知识库中遍历每个已经上传的文件名并组合在一起（未保存的状态下）
			hasUploadFileKnowledgeName += "-s="+$(this).text().replace("删除","");
		});
		
		if(tabsId!=""){ //在非知识库模块中才存在该id
			$("#"+tabsId+" td[align='left'] a").each(function(){ //非知识库已上传的文件字符串
				hasUploadFileSoonName += "-s=" + $(this).html();
			});
		}
		$("#idFileList"+type+" td:even").each(function(){ //遍历每个要上传的文件名并组合在一起
			var _uploadFilename = $(this).html();
			if(_uploadFilename.indexOf("/")!=-1){
				_uploadFilename = _uploadFilename.substring(_uploadFilename.lastIndexOf("/")+1);
			}
			if(_uploadFilename.indexOf("\\")!=-1){
				_uploadFilename = _uploadFilename.substring(_uploadFilename.lastIndexOf("\\")+1);
			}
			msgAlert(_uploadFilename);
			uploadFileNames+="-s="+_uploadFilename;
		});
		uploadFileNames = uploadFileNames.substring(3);  //去掉开头的“-s=”符号
			for(var i = 0 ; i <  uploadFileNames.split("-s=").length ; i ++){//遍历所有要上传的文件是否存在于已上传的文件
				if(hasUploadFileName.indexOf(uploadFileNames[i])!=-1||hasUploadFileSoonName.indexOf(uploadFileNames[i])!=-1
						||hasUploadFileKnowledgeName.indexOf(uploadFileNames[i])!=-1){
					msgAlert("已经有相同文件","info");
					return false;
				}
				
			}
		
		if(fu.Files.length <= 0){
			msgShow(i18n.please_add_attachement,"show");
			return false;
		}
		//startProcess();
		//显示文件列表
		var arrRows = [];
		Each(fu.Files, function(o){arrRows.push([o.value, "&nbsp;"]); });
		AddList(arrRows,type);
		$("#idMsg"+type).show();
		//var url='file.jsp?eno='+eno+'&eventType='+eventType+'&createor='+encodeURI(encodeURI(createor));
		$('#uploadForm'+type).form("submit",{  
			url: "common/tools/file.jsp",
			type:"post",
			dataType : 'json', 
	        success:function(data){
	        /*	if(data.indexOf("成功")>0){
	        		common.tools.event.eventAttachment.showEventAttachment(tabsId,eno,eventType,true);
	        		msgShow("上传成功！","info");
	        	}else */
	        	if(data.indexOf("-s-")>0){
	        		data=decodeURI(data);
	        		$("#"+valueId).val($("#"+valueId).val()+data);//隐藏域的值
	        		if(eno!==""){
	        			if(type==="_CiEdit"||type==="_CiInfo")
	        				common.tools.event.eventAttachment.saveAttachment(tabsId,eno,eventType,valueId,true);
	        			else
	        				common.tools.event.eventAttachment.saveEventAttachment(createor,tabsId,eno,eventType,valueId,true);
		        		msgShow(i18n.lable_addRequest_upload_success,"show");
	        		}else{
		        		var attrArr=data.split("-s-");
		        		for(var i=0;i<attrArr.length;i++){
		        			var attr=attrArr[i]+"";
		    				if(attr!=null && attr.length>0){
		            			var attrArrs=attr.split("==");
		            			var fileName=attrArrs[1];
				        		var attachIcon="../images/attachicons/unknown.gif";
								var fileFix=fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
								if(fileFix==".rar"){
									attachIcon="../images/attachicons/rar.gif";
								}else if(fileFix==".zip"){
									attachIcon="../images/attachicons/zip.gif";
								}else if(fileFix==".gif"||fileFix==".jpg"||fileFix==".bmp"||fileFix==".png"){
									attachIcon="../images/attachicons/image.gif";
								}else if(fileFix==".doc"||fileFix==".docx"||fileFix==".xls"||fileFix==".ppt"||fileFix==".pptx"||fileFix==".xlsx"){
									attachIcon="../images/attachicons/msoffice.gif";
								}else if(fileFix==".pdf"){
									attachIcon="../images/attachicons/pdf.gif";
								}else if(fileFix==".swf"){
									attachIcon="../images/attachicons/flash.gif";
								}else if(fileFix==".txt"){
									attachIcon="../images/attachicons/text.gif";
								}
								//获取去除路径的文件名
								attrArrs[0] = attrArrs[0].indexOf("\\")!=-1?attrArrs[0].substring(attrArrs[0].lastIndexOf("\\")+1,attrArrs[0].lastIndexOf(".")):attrArrs[0];
								var htmlCode="<div id='"+fileName.substring(fileName.lastIndexOf("\\")+1,fileName.lastIndexOf("."))+"' ><img width='14px' height='14px' src='"+attachIcon+"' />&nbsp;&nbsp;"+attrArrs[0]+"&nbsp;&nbsp;<a  href=javascript:deleteFile('"+fileName+"','"+fileList+"','"+valueId+"')>"+i18n['deletes']+"</a><br/>";
								$("#"+fileList).append(htmlCode);
		    				}
		        		}
	        		}
	        	}else
	        		msgShow(i18n.lable_addRequest_upload_errors,"show");
	        	fu.Clear();
	        	endProcess();
	        }  
		}); 
	};

}

//用来添加文件列表的函数
function AddList(rows,type){
	//根据数组来添加列表
	var FileList = $will("idFileList"+type), oFragment = document.createDocumentFragment();
	//用文档碎片保存列表
	Each(rows, function(cells){
		var row = document.createElement("tr");
		Each(cells, function(o){
			var cell = document.createElement("td");
			if(typeof o == "string"){ cell.innerHTML = o; }else{ cell.appendChild(o); }
			row.appendChild(cell);
		});
		oFragment.appendChild(row);
	});
	//ie的table不支持innerHTML所以这样清空table
	while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); }
	FileList.appendChild(oFragment);
}


//在后台通过window.parent来访问主页面的函数
function Finish(msg){ 
	msg=msg.replace(/<br[^>]*>/ig,"\n").replace(/&nbsp;/ig,"   ");
	msgAlert(msg);
	location.href = location.href; 
}
